package com.base.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.base.sys.entity.SysRole;
import com.base.sys.entity.SysRolePermission;
import com.base.sys.entity.SysUserRole;
import com.base.sys.mapper.SysRoleMapper;
import com.base.sys.mapper.SysRolePermissionMapper;
import com.base.sys.mapper.SysUserRoleMapper;
import com.base.sys.service.ISysRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.base.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author gjj
 * @since 2018-11-27
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysRolePermissionMapper sysRolePermissionMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    public Page selectPageNew(Page page, Wrapper wrapper){
        return sysRoleMapper.selectPageNew(page,wrapper);
    }

    @Override
    @Transactional
    public Result deleteBatch(List<SysRole> list){
        List<String> ids = list.stream().map(sysRole -> {
            return sysRole.getId();
        }).collect(Collectors.toList());
        sysRoleMapper.deleteBatchIds(ids);
        QueryWrapper<SysRolePermission> queryWrapper=new QueryWrapper<SysRolePermission>();
        queryWrapper.in("ROLE_ID",ids);
        sysRolePermissionMapper.delete(queryWrapper);

        QueryWrapper<SysUserRole> userRoleQueryWrapper=new QueryWrapper<SysUserRole>();
        userRoleQueryWrapper.in("ROLE_ID",ids);
        sysUserRoleMapper.delete(userRoleQueryWrapper);
        return Result.successResult();
    }

    @Transactional
    @Override
    public Result assignPerm(SysRole role){
        String id = role.getId();
        Long[] permIds = role.getPermIds();
        QueryWrapper<SysRolePermission> queryWrapper=new QueryWrapper<SysRolePermission>();
        queryWrapper.eq("ROLE_ID",id);
        sysRolePermissionMapper.delete(queryWrapper);
        for(Long permId:permIds){
            if(permId<10000){
                SysRolePermission rolePermission=new SysRolePermission();
                rolePermission.setPermissionId(permId.toString());
                rolePermission.setRoleId(id);
                sysRolePermissionMapper.insert(rolePermission);
            }

        }
        return Result.successResult();
    }

}
